package cn.com.common.job.task;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import cn.com.common.constants.Constants;
import cn.com.gas.entity.GasOfflineCamEntity;
import cn.com.gas.entity.GasServerAreaEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.service.GasOfflineCamService;
import cn.com.gas.service.GasServerAreaService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.util.HmacSha256Utils;
import cn.com.util.MD5Utils;
import cn.com.util.RestTemplateUtil;
import cn.com.util.TsBqUtils;

/**
 * 定时任务(演示Demo，可删除) testTask为spring bean的名称， 方法名称必须是run
 *
 * @author wenbin
 * @version V1.0
 * @date 2020年3月18日
 */
@Component("gasStationInfoMonitoringProcessTask")
@DisallowConcurrentExecution
public class GasStationInfoMonitoringProcessTask {
	
	@Value("${gasstation.timedTask.gasStationInfoMonitoringProcessTask}")
	private String gasStationInfoMonitoringProcessTask;
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private GasServerAreaService gasServerAreaService;
	@Autowired
	private GasOfflineCamService gasOfflineCamService;

	@Value("${gasstation.videosQueryVideoGetGroupsOfflineUrl}")
	private String url;

	@Value("${gasstation.thirdPartyPass}")
	private String pass;
	@Value("${gasstation.thirdPartyUser}")
	private String user;
	
	public void run(String params) throws Exception {
		logger.debug("gasStationInfoMonitoringProcessTask定时任务正在执行，参数为：{}", params);
		logger.debug("application参数为gasStationInfoMonitoringProcessTask：{}", gasStationInfoMonitoringProcessTask);

		if (gasStationInfoMonitoringProcessTask.equals(Constants.JOB_STOP)) {

			logger.debug("application配置文件控制不执行gasStationInfoMonitoringProcessTask定时任务");
			throw new Exception("application配置文件控制不执行gasStationInfoMonitoringProcessTask定时任务");
		
		}
		
		
		Date date = new Date();

		// 创建一个SimpleDateFormat对象，定义日期格式
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		// 将Date对象转换为指定格式的字符串
		String dateString = formatter.format(date);

		// String url =
		// "http://21.0.0.60:5000/Videos/QueryVideo/GetGroupsOffline";

		List<GasServerAreaEntity> list = gasServerAreaService.list();

		for (GasServerAreaEntity gasServerAreaEntity : list) {
			String camid = gasServerAreaEntity.getCamid();
			Map<String, Object> map = new HashMap<>();
			map.put("api", user);
			map.put("isMobile", "1");
			map.put("offline", "0");
			map.put("id", camid);
			map.put("parentType", "cam");
			map.put("sign", sign(url, map));
			String domainResponse = removeFirstAndLastChar(RestTemplateUtil.get(url, map));
			if (TsBqUtils.isNotNull(domainResponse)) {
				JSONArray domainJsonArray = JSONArray.parseArray(domainResponse);
				List<GasStationinfoEntity> listDomain = JSONArray.parseArray(JSON.toJSONString(domainJsonArray),
						GasStationinfoEntity.class);
				
				for (GasStationinfoEntity domain : listDomain) {
					saveOrUpdateGasStationinfo(domain);
					
					String id = domain.getId();
					String online = domain.getOnline();
					GasOfflineCamEntity offlineCamEntity = gasOfflineCamService.getById(id);
					if (TsBqUtils.isNotNull(offlineCamEntity) && online.equals("0")) {
						// 已离线、未恢复

					} else if (TsBqUtils.isNotNull(offlineCamEntity) && !online.equals("0")) {
						// 已离线、恢复在线

						offlineCamEntity.setRecoverTime(dateString);
						offlineCamEntity.setId(id + "_" + TsBqUtils.getUUID());
						gasOfflineCamService.save(offlineCamEntity);

						gasOfflineCamService.realDelete(id);
					} else if (TsBqUtils.isNull(offlineCamEntity) && online.equals("0")) {
						// 新离线
						GasOfflineCamEntity gasOfflineCamEntity = new GasOfflineCamEntity();
						String pid = domain.getPid();
						GasStationinfoEntity stationinfoPid = gasStationinfoService.getById(pid);
						
						gasOfflineCamEntity.setId(id);
						gasOfflineCamEntity.setTaxorgName(stationinfoPid.getTaxorgcode());
						gasOfflineCamEntity.setStationName(pid);
						gasOfflineCamEntity.setCamId(id);
						gasOfflineCamEntity.setOfflineTime(dateString);
						gasOfflineCamEntity.setDeleted(Constants.DATA_NOT_DELETED);
						gasOfflineCamEntity.setCreateTime(date);

						gasOfflineCamService.save(gasOfflineCamEntity);
						
						
					} else {

					}

				}
			}
		}

	}

	private void saveOrUpdateGasStationinfo(GasStationinfoEntity gasStationinfo) {
		Date date = new Date();

		String id = gasStationinfo.getId();
		GasStationinfoEntity gasStationinfoEntity = gasStationinfoService.getById(id);

		if (TsBqUtils.isNotNull(gasStationinfoEntity)) {

			gasStationinfo.setAddress(gasStationinfoEntity.getAddress());
			gasStationinfo.setTaxorgcode(gasStationinfoEntity.getTaxorgcode());
			gasStationinfo.setIsAnalyse(gasStationinfoEntity.getIsAnalyse());

		}

		gasStationinfo.setIsAnalyse("Y");

		gasStationinfo.setCreateTime(date);
		gasStationinfo.setDeleted(Constants.DELETEED_NOT);
		gasStationinfoService.saveOrUpdate(gasStationinfo);
	}

	private String sign(String url, Map<String, Object> parameter) throws UnsupportedEncodingException {
		if (!parameter.isEmpty()) {
			url = url + "?";
			for (String key : parameter.keySet()) {
				url = url + key + "=" + parameter.get(key) + "&";
			}
			url = url.substring(0, url.length() - 1);
		}

		String encrypt = MD5Utils.encrypt(pass);
		byte[] hmacSHA256 = HmacSha256Utils.hmacSHA256(url, encrypt);
		byte[] encodedBytes = Base64.getEncoder().encode(hmacSHA256);
		String encodedString = URLEncoder.encode(new String(encodedBytes), "UTF-8");

		return encodedString;
	}

	public String removeFirstAndLastChar(String s) {
		if (s.length() <= 2) {
			return ""; // 如果字符串长度小于等于2，则返回空字符串
		}
		String str = s.substring(1, s.length() - 1);
		String replaceAll = str.replaceAll("\\\\", "");
		return replaceAll;

	}

}
